import math

from django.db import connection
from django.shortcuts import render
from django.views import View
from django.core.paginator import Paginator

from blog import models
from blog.mypage import MyPagination


class IndexView(View):
    def get(self,request,num=1):
        num = int(num)
        # print("num: ",num)
        postlist = models.Post.objects.all().order_by('-created')
        page_obj = Paginator(postlist,2)
        postlist = page_obj.page(num)
        last_page = page_obj.num_pages
        # print("last_page: ",last_page)
        begin = num - math.ceil(5.0/2)
        if begin < 1:
            begin = 1
        end = begin + 5
        if end > last_page:
            end = last_page
        if end < 5:
            begin = 1
        else:
            begin = end -5
        page_list = range(begin,end + 1)
        return render(request,'home.html',{'postlist':postlist,'num':num,'last_page':last_page,'page_list':page_list})


class DetailView(View):
    def get(self,request,postid):
        postid = int(postid)
        post = models.Post.objects.filter(id=postid).first()
        return render(request,'detail.html', {'post': post})


def tag_archive(request,tag):
    # print(request.path)
    # print("tag: ",tag,type(tag))
    cursor = connection.cursor()
    r_post = cursor.execute(f"select t_post.id,t_post.title,t_post.created from t_post,t_post_tag,t_tag where t_post.id=t_post_tag.post_id and t_post_tag.tag_id = t_tag.id and t_tag.tag = '{tag}' order by t_post.created desc").fetchall()
    page_obj = MyPagination(request, r_post)
    context = {
        "postlist": page_obj.postlist,  # 分完页后的数据
        "page_string": page_obj.html_page()  # 生成页码
    }
    # print("postlist: ",len(page_obj.postlist),page_obj.postlist)
    return render(request,'postlist.html',context)


def date_archive(request,year=1,month=1):
    year = int(year)
    month = int(month)
    if year == 1 and month == 1:
        c_post = models.Post.objects.all().values("id","title","created","category__category","tag__tag").order_by('-created')
    else:
        c_post = models.Post.objects.filter(created__year=year,created__month=month).values("id","title","created","category__category","tag__tag").order_by('-created')
    # for c in c_post:
    #     print("c_category: ",c)
    page_obj = MyPagination(request, c_post)
    context = {
        "cpostlist": page_obj.postlist,  # 分完页后的数据
        "page_string": page_obj.html_page()  # 生成页码
    }
    # print("cpostlist: ", len(page_obj.postlist), page_obj.postlist)
    return render(request,'postlist.html',context)